package com.qianchang.microfinance.view.mine.bill;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.OneLineLinearLayout;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.PreReplyPrincipalBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.hsrecharge.HSReChargeActivity;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: 提前还款
 * 修 改 人: zhoulai
 * 修改时间: 2017/8/17 14:41
 */


public class PrePayBackActivity extends BaseActivity{

    private static final String TAG = "PrePayBackActivity";

    @BindView(R.id.oll_payback_amount)//本金
    OneLineLinearLayout ollPaybckAmount;

    @BindView(R.id.oll_interest)//利息
    OneLineLinearLayout ollInterest;

    @BindView(R.id.ill_Liquidated_damages)//违约金
    OneLineLinearLayout illLiquidatedDamages;

    @BindView(R.id.oll_repay_total_amount)//总额
    OneLineLinearLayout ollRepayTotalAmount;

    @BindView(R.id.style_common_one_line_not_go)//需还款金额
    OneLineLinearLayout style_common_one_line_not_go;

    @BindView(R.id.oll_warming)//警告
    TextView ollWarming;

    @BindView(R.id.lld_pre_payback)//操作按钮
    LinearLayout lldPrepayback;

    @BindView(R.id.btn_pre_payback)
    Button btnPrePayback;

    @BindView(R.id.btn_pre_charge)
    Button btnPrePayCharge;

    @BindView(R.id.btn_old_payback)
    Button btnOldPayback;

    private String projectId;
    private double unrepayPrincipal;//未还本金
    private double unrepayInterest;//利息
    private double unrepayAllpay;//总额

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_payback);
        ButterKnife.bind(this);
        initView();
        initData();
        getPrincipal();
    }


    @Override
    protected void initView() {
        super.initView();
        setTitleName(getString(R.string.Label_reply_advance));
        btnPrePayback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog alertDialog = new AlertDialog.Builder(PrePayBackActivity.this)
                        .setTitle("提示")
                        .setMessage("是否执行提前还款？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //执行提前还款
                                dialog.dismiss();
                                payback();
                            }
                        }).setCancelable(false).create();
                alertDialog.show();
            }
        });
        //去充值
        btnPrePayCharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //去充值
                Bundle bundle = new Bundle();
                bundle.putString("money",unrepayAllpay+"");
                bundle.putString("rechargeType","3");
                startActivity(HSReChargeActivity.class,bundle,true);
            }
        });
        //逾期还款
        btnOldPayback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(MyBillActivity.class);
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (null != bundle) {
            projectId = bundle.getString(ConstantAppInfo.PROJECT_ID);
        }
    }

    /**
     * 计算还款金额
     */
    private void getPrincipal() {
        show();
        HttpParams params = new HttpParams();
        params.put("projectId", projectId); //项目id
        params.put("userId", DMApplication.getInstance().getmUserLoginInfo().getUserId());
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.PRE_REPAY_GET, params, new RequestCallBack<PreReplyPrincipalBean>() {
            @Override
            public void onSuccess(JsonResult<PreReplyPrincipalBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    PreReplyPrincipalBean preReplyPrincipalBean = response.getObject();
                    if (preReplyPrincipalBean == null)
                        preReplyPrincipalBean = new PreReplyPrincipalBean();
                    try {
                        unrepayPrincipal = preReplyPrincipalBean.getPrincipal();
                        unrepayInterest = preReplyPrincipalBean.getInterest();
                        unrepayAllpay = unrepayPrincipal + unrepayInterest;
                        ollPaybckAmount.setRightContent(FormatUtil.numKbPointFormat(unrepayPrincipal));//本金
                        ollInterest.setRightContent(FormatUtil.numKbPointFormat(unrepayInterest));//利息
                        illLiquidatedDamages.setRightContent(FormatUtil.numKbPointFormat("0.00"));//违约金
                        ollRepayTotalAmount.setRightContent(FormatUtil.numKbPointFormat(preReplyPrincipalBean.getTotalMoney()));//还款总额
                        style_common_one_line_not_go.setRightContent(FormatUtil.numKbPointFormat(preReplyPrincipalBean.getRechargeMoney()));//需充值金额
                        if (preReplyPrincipalBean.getDaihuan()>0){
                            ollWarming.setVisibility(View.VISIBLE);
                            lldPrepayback.setVisibility(View.GONE);
                            btnOldPayback.setVisibility(View.VISIBLE);
                        }else{
                            ollWarming.setVisibility(View.GONE);
                            lldPrepayback.setVisibility(View.VISIBLE);
                            btnOldPayback.setVisibility(View.GONE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.getInstant().show(PrePayBackActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(PrePayBackActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(PrePayBackActivity.this, msg);
            }
        });
    }

    /**
     * 执行还款
     */
    private void payback() {
        show();
        HttpParams params = new HttpParams();
        params.put("projectId", projectId); //项目id
        params.put("period","0");//还款期数
        params.put("principal", unrepayPrincipal);//还款本金
        params.put("interest", unrepayInterest);//还款利息
        params.put("overdue","0.00");//逾期金额
        /**
         * 订单类型：1：开通会员 2：充值金币  3：充值余额  4：手工提现 5：自动提现 6.余额正常还款 7.银行卡正常还款
         * 8.余额逾期还款 9.银行卡逾期还款 10.代还
         */
        params.put("rechargeType","6");//还款处理
        params.put("userId", DMApplication.getInstance().getmUserLoginInfo().getUserId());

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.PRE_REPAY_DO, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    startActivity(MyBillActivity.class,true);
                } else {
                    if(response.getDescription().equals("账户余额不足")){
                        final AlertDialog alertDialog = new AlertDialog.Builder(PrePayBackActivity.this)
                                .setTitle("提示")
                                .setMessage("账户余额不足,是否立即执行充值操作？")
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //执行提前还款
                                        dialog.dismiss();
                                        //去充值
                                        Bundle bundle = new Bundle();
                                        bundle.putString("money",unrepayAllpay+"");
                                        bundle.putString("rechargeType","3");
                                        startActivity(HSReChargeActivity.class,bundle,true);
                                    }
                                }).setCancelable(false).create();
                        alertDialog.show();
                    }else{
                        ToastUtil.getInstant().show(PrePayBackActivity.this, response.getDescription());
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(PrePayBackActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }
}
